package com.huahai.security.core.validate.code.mobile.sms;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: Jun
 * @Date: 2020/7/20
 *
 * 默认的短信发送器，通过阿里云发送
 */
public class DefaultSmsCodeSender implements SmsCodeSender {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    private static final String ACCESS_KEY_ID = "LTAIBMY4blEThfyl";
    private static final String ACCESS_KEY_SECRET = "Tnxhqc6bRn1BPIh4s5NSwQVPR7Qgek";
    private static final String SMS_SIGN_NAME = "华海科技";
    private static final String SMS_LOGIN_TEMPLATE = "SMS_162855530";

    @Override
    public void send(String mobile, String code) {
        CommonResponse response = sendSms(mobile, code);
        logger.info("向用户{}发送验证码： {}",mobile,code);
    }

    public static CommonResponse sendSms(String phone, String code) {
        DefaultProfile profile = DefaultProfile.getProfile("default", ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", SMS_SIGN_NAME);
        request.putQueryParameter("TemplateCode", SMS_LOGIN_TEMPLATE);
        request.putQueryParameter("TemplateParam", String.format("{'code': '%s'}", code));

        CommonResponse response = null;
        try {
            response = client.getCommonResponse(request);
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return response;
    }

}
